package dao.impl;

import dao.BaseDao;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;

import java.io.Serializable;
import java.util.List;

public class BaseDaoHibernate4<T> implements BaseDao<T> {
    private SessionFactory sessionFactory;

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    @Override
    public T get(Class<T> entityClazz, Serializable id) {
        return getSessionFactory().getCurrentSession().get(entityClazz, id);
    }

    @Override
    public Serializable save(T entity) {
        return getSessionFactory().getCurrentSession().save(entity);
    }

    @Override
    public void update(T entity) {
        getSessionFactory().getCurrentSession().saveOrUpdate(entity);
    }

    @Override
    public void delete(T entity) {
        getSessionFactory().getCurrentSession().delete(entity);
    }

    @Override
    public void delete(Class<T> entityClazz, Serializable id) {
        getSessionFactory().getCurrentSession()
                .createQuery("delete "+entityClazz.getSimpleName()+" en where en.id = ?0")
                .setParameter("0", id)
                .executeUpdate();
    }

    @Override
    public List<T> findAll(Class<T> entityClazz) {
        return null;
    }

    @Override
    public long findCount(Class<T> entityClazz) {
        return 0;
    }

    @SuppressWarnings("unchecked")
    protected  List<T> find(String hql){
        return (List<T>) getSessionFactory().getCurrentSession()
                .createQuery(hql).list();
    }

    @SuppressWarnings("unchecked")
    protected  List<T> find(String hql, Object... params){
        Query query = getSessionFactory().getCurrentSession().createQuery(hql);
        for (int i = 0; i < params.length; i++) {
            query.setParameter(i, params[i]);
        }
        return (List<T>) query.list();
    }

    @SuppressWarnings("unchecked")
    protected List<T> findByPages(String hql, int pageNo, int pageSize){
        return getSessionFactory().getCurrentSession().createQuery(hql)
                .setFirstResult((pageNo-1)*pageSize)
                .setMaxResults(pageSize)
                .list();
    }

    @SuppressWarnings("unchecked")
    protected List<T> findByPages(String hql, int pageNo, int pageSize, Object... params){
        Query query = getSessionFactory().getCurrentSession().createQuery(hql);
        for (int i = 0; i < params.length; i++) {
            query.setParameter(i, params[i]);
        }
        return query.setFirstResult((pageNo-1)*pageSize)
                .setMaxResults(pageSize)
                .list();
    }

}
